//
//  EmoticonsManager.swift
//  EmoticonKeyBoard
//
//  Created by apple on 15/12/25.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit


//负责从 plist 文件中 加载表情数据
class EmoticonsManager: NSObject {

    
    //定义 单例对象
    static let sharedEmoticonManager = EmoticonsManager()
    //分组表情数组
    lazy var packages = [EmoticonPackages]()
    
    //实例化的时候记载分组表情
    //将初始化方法私有化
    private override init() {
        super.init()
        //换成单例对象 只会加载一次
        loadEmoticons()
    }
    
    
    func statusTextToImagwText(str: String, font: UIFont) -> NSAttributedString {
        
        let pattern = "\\[.*?\\]"
        
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        // 需要表情数组 表情文字 在 表情数据源中 查找 表情模型
        // matchesInString  会进行多次查找
        let results = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: str.characters.count))
        //遍历结果集   倒序
        var index = results.count - 1
        //获取表情数据源的数组
        let strM = NSMutableAttributedString(string: str)
        while index >= 0 {
            let result = results[index]
            let range = result.rangeAtIndex(0)
            let subStr = (str as NSString).substringWithRange(range)
            //            print(subStr)
            //获取到表情模型
            if let em = getEmoticonWithEmoticonText(subStr) {
                //表情模型 中 有图片地址
                
                
                let imageText = EmoticonTextAttachment().emoticonTextToImageText(em,font: font)
                //将图片转换为 附件 -> 富文本
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            
            index--
        }
        //替换富文本
        return strM
    }
    
    private func getEmoticonWithEmoticonText(str: String) -> Emoticon? {
        let packages = EmoticonsManager.sharedEmoticonManager.packages
        for p in packages {
            //filter  过滤 滤镜
            let emoticones =  p.emoticones.filter({ (em) -> Bool in
                //返回一个过滤条件
                return em.chs == str
            })
            
            if emoticones.count != 0 {
                return emoticones.last
            }
        }
        
        return nil
    }
    
    func loadEmoticons() {
        // 1.获取bundle 文件目录
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        //判断path 是否为空
        guard let filePath = path else {
            print("文件目录不存在")
            return
        }
        
//        print(filePath)
        // 2加载plist文件 转换为 字典
        let dict = NSDictionary(contentsOfFile: filePath)!
        // 3.获取字典中的数据 遍历数据 获取分组表情目录中 Info.plist文件
        if let array = dict["packages"] as? [[String : AnyObject]] {
            //遍历数据
            for item in array {
                let id = item["id"] as! String
                //获取分组表情的目录 加载 分组目录中 Info.plist
                loadGroupEmoticons(id)
            }
        }
    }
    
    
    private func loadGroupEmoticons(id: String) {
        let path = NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil, inDirectory: "Emoticons.bundle/" + id)
        guard let filePath = path else {
            print("文件目录不存在")
            return
        }
        
        //一定加载到Info.plist 文件
        let dict = NSDictionary(contentsOfFile: filePath)!
//        print(dict)
        let group_name_cn = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String : String]]
//        print(group_name_cn,"+++++++++++++",array)
        //实例化packages 对应的模型
        let p = EmoticonPackages(id: id, group_name_cn: group_name_cn, array: array)
        packages.append(p)
        print(p)
    }
}
